import React, { PureComponent } from "react";
import { connect } from "dva";
// import { routerRedux, Link } from 'dva/router';
import { Form, Input, Button, Row, Col, Cascader, Steps, message,Checkbox } from "antd";
import "./PersonalRegistration.less";
import {
  getDistrictData, //省市区选择
  // getDistrictChineseData,
  systemPerAccountInfoVerificationPhone, //联系人手机验证接口
  systemPlatNewsSendVerificationCode, //获取验证码接口
  systemPlatNewsVerificationCode, //验证短信验证码接口
  systemPerAccountInfoSave //注册接口
} from "../../services/api";
import bcx_utils from "../../common/bcx_utils";
import IconS from "../../components/IconS";

const FormItem = Form.Item;
const { Step } = Steps;

@connect(state => ({
  register: state.register
}))
@Form.create()
export default class PersonalRegistration extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      count: 0,
      areas: [] //省市区
    };
  }
  /******************************生命周期******************************/

  componentDidMount = () => {
    this.getDistrict(); //省市区选择
  };

  componentWillUnmount = () => {
    clearInterval(this.interval);
  };

  /******************************相关事件******************************/
  onGetCaptcha = () => {
    this.getMobileVerificationCode();
  };
  /******************************ajax请求******************************/
  //省市区
  getDistrict = () => {
    getDistrictData().then(res => {
      console.log("个人注册省市区:", res);
      const areas = res.data.map(val => {
        return {
          value: val.regionId,
          label: val.regionName,
          children: val.childs.map(valChild => {
            return {
              value: valChild.regionId,
              label: valChild.regionName,
              children: valChild.childs.map(valChildChild => {
                return {
                  value: valChildChild.regionId,
                  label: valChildChild.regionName
                };
              })
            };
          })
        };
      });
      this.setState({ areas });
      //console.log('areas:'+JSON.stringify(areas));
    });
  };
  //获取验证码
  getMobileVerificationCode = () => {
    const mobile = this.props.form.getFieldValue("mobile");
    console.log("手机号码", mobile);
    if (!mobile || mobile === null) {
      message.error("联系手机不能为空！");
    }
    if (mobile && mobile !== null && mobile.length === 11) {
      systemPerAccountInfoVerificationPhone({ mobile })
        .then(() => {
          let count = 59;
          this.setState({ count });
          this.interval = setInterval(() => {
            count -= 1;
            this.setState({ count });
            if (count === 0) {
              clearInterval(this.interval);
            }
          }, 1000);

          systemPlatNewsSendVerificationCode({ mobile }).then(
            res => {
              console.log("验证码是否发送成功:", res);
            },
            err => {
              console.log("获取验证码错误信息:", err);
            }
          );
        })
        .catch(err => {
          console.log("验证码处手机号码是否被注册:", err);
          message.error(err);
        });
    }
  };

  handleSubmit = e => {
    e.preventDefault();

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log("Received values of form1111: ", values);
      }
    });

    //验证手机号码是否被注册
    const mobile = this.props.form.getFieldValue("mobile");
    const code = this.props.form.getFieldValue("code");
    const verificationCodeData = { mobile, code };
    if (mobile && mobile.length === 11) {
      // bcx_utils.preventRepeatAsync(callback => callback((resolve) => {
      systemPerAccountInfoVerificationPhone({ mobile }).then(
        res => {
          if (res.retType === "0") {
            console.log("手机号码未注册");

            systemPlatNewsVerificationCode(verificationCodeData).then(
              codeRes => {
                console.log("验证短信验证码接口", codeRes);
                if (codeRes.retType === "0") {
                  console.log("验证码正确");

                  this.props.form.validateFieldsAndScroll((err, values) => {
                    if (!err) {
                      console.log("Received values of form1111: ", values);

                      const residence = this.props.form.getFieldValue(
                        "residence"
                      );
                      const phone = this.props.form.getFieldValue("mobile");
                      let province;
                      let city;
                      let area;
                      if (residence) {
                        [province, city = "", area = ""] = [
                          residence[0],
                          residence[1],
                          residence[2]
                        ];
                        // province = residence[0];
                        // city = residence[1];
                        // area = residence[2];
                      }
                      const submitData = {
                        phone,
                        province,
                        city,
                        area
                      };
                      console.log(submitData);
                      bcx_utils.preventRepeatAsync(callback =>
                        callback(resolve => {
                          systemPerAccountInfoSave(submitData).then(
                            submitRes => {
                              resolve(false);
                              console.log("注册接口", submitRes);
                              message.success("注册成功！");

                              if (window.top === window.self) {
                                this.props.history.push(
                                  "PersonalRegistrationResult"
                                );
                              } else {
                                const url = window.location.href.split("#")[0];
                                window.top.location = url + "#/user/PersonalRegistrationResult";
                              }
                            },
                            error => {
                              message.error(error, 2, () => {
                                resolve(false);
                              });
                            }
                          );
                        })
                      );
                    }
                  });
                }
              },
              err => {
                message.error(err);
              }
            );
          }
        },
        err => {
          message.error(err);
        }
      );
      // }));
    }
  };

  /******************************render******************************/

  render() {
    const { count } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 20 }
      }
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 18,
          offset: 4
        }
      }
    };

    return (
      <div className="PersonalRegistration" style={{ height: window.top !== window.self && 'auto' }}>
        <div className="enroll-header" style={{ display: window.top !== window.self && 'none' }}>
          <div className="head-portrait">
            {/*<span className="head-portrait-con" />*/}
            <IconS type="logo-" />
            <span className="head-portrait-text">
              <span style={{ fontSize: "18px" }}>百保盾</span>
              <br />
              <span style={{ fontSize: "12px" }}>改变工作 改变你</span>
            </span>
          </div>
          <div className="head-portrait-register">
            <span
              style={{ cursor: "pointer" }}
              onClick={() => this.props.history.push("LogOn")}
            >
              登录
            </span>
          </div>
        </div>
        <div className="container" style={{ margin: window.top !== window.self && '0px' }}>
          <div className="main" style={{ marginLeft: window.top !== window.self && '0px', padding: window.top !== window.self && '0px', width: window.top !== window.self && '490px' }}>
            <h3>个人注册</h3>
            <div
              className="progress-bar"
              style={{ marginLeft: "45px", marginRight: "36px" }}
            >
              <Steps>
                <Step title="填写注册资料" />
                <Step title="注册成功" />
              </Steps>
            </div>
            <Form onSubmit={this.handleSubmit} style={{ marginTop: "40px", width: window.top !== window.self && '490px' }}>
              <FormItem {...formItemLayout} label="所属城市">
                {getFieldDecorator("residence", {
                  // initialValue: ['浙江', '杭州', '西湖'],
                  rules: [
                    {
                      type: "array",
                      required: true,
                      message: "请选择你的所属城市!"
                    }
                  ]
                })(
                  <Cascader
                    showSearch
                    options={this.state.areas}
                    placeholder="请选择"
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="联系手机">
                <Row gutter={8}>
                  <Col span={24}>
                    {getFieldDecorator("mobile", {
                      rules: [
                        {
                          required: true,
                          message: "请输入手机号!"
                        },
                        {
                          pattern: /^1[0-9]{10}$/,
                          message: "手机号格式错误！"
                        }
                      ]
                    })(
                      <div>
                        <Input placeholder="请输入" maxLength="11" />
                      </div>
                    )}
                  </Col>
                </Row>
              </FormItem>
              <FormItem {...formItemLayout} label="验证码">
                <Row gutter={8}>
                  <Col span={18}>
                    {getFieldDecorator("code", {
                      rules: [
                        {
                          required: true,
                          message: "请输入验证码！"
                        }
                      ]
                    })(
                      <div>
                        <Input placeholder="请输入" maxLength="8" />
                      </div>
                    )}
                  </Col>
                  <Col span={6}>
                    <Button
                      type="primary"
                      disabled={count}
                      className="getCaptcha"
                      onClick={this.onGetCaptcha}
                    >
                      {count ? `${count} s` : "获取验证码"}
                    </Button>
                  </Col>
                </Row>
              </FormItem>
              <FormItem {...tailFormItemLayout} >
                {getFieldDecorator('remember', {
                  valuePropName: 'checked',
                  initialValue: true,
                })(
                  <div>
                  <Checkbox  onChange={this.onChange}> </Checkbox>
                  <span style={{marginTop:-38,display:"block",marginLeft:14}}>勾选即同意<a className="login-form-forgot" target="_blank"
                      onClick={
                        () => {
                          if (window.top === window.self) {
                            const url = window.location.href.split("#")[0];
                            window.open(url + "#/user/UserAgreement",'_blank');
                          } else {
                            const url = window.location.href.split("#")[0];
                            window.top.location = url + "#/user/UserAgreement";
                          }
                        }}
                    >《用户服务协议》</a>
                    和<a className="login-form-forgot" target="_blank"
                      onClick={
                        () => {
                          if (window.top === window.self) {
                            const url = window.location.href.split("#")[0];
                            window.open(url + "#/user/UserPlicy",'_blank');
                          } else {
                            const url = window.location.href.split("#")[0];
                            window.top.location = url + "#/user/UserPlicy";
                          }
                        }
                      }
                    >《隐私策略》</a>
                  </span></div>
                )}
                <p style={{ color: 'red' }}> {this.state.errtext}</p>
                <Button
                  onClick={() => this.props.history.push("Enroll")}
                  style={{ marginRight: "16px", visibility: window.top !== window.self && 'hidden' }}
                >
                  取消
                </Button>
                <Button className="submit" type="primary" htmlType="submit">
                  确定
                </Button>
                {/* <Link className="login" to="/user/login">使用已有账户登录</Link> */}
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
    );
  }
}
